﻿using System;
using Shoozla.DataModel;
using System.Net;
using System.IO;
using System.Drawing;
using System.Windows;
using System.Threading.Tasks;
using Shoozla.View;
using MahApps.Metro.Controls;
using System.Windows.Controls;
using System.Windows.Forms;


namespace Shoozla.ViewModel
{
    public class ID3TagEditorViewModel : ViewModelBase
    {
        #region Variables
        
        private bool _isPlaying;

        private Mp3File _originalSong;
        private Mp3File _song;
        public Mp3File Song
        {
            get { return _song; }
            set
            {
                if (_song != value)
                {
                    _originalSong = value;
                    
                    //refresh of the image, otherwise display the cover in memory
                    if (_originalSong.HasCover && _originalSong.Cover == null)
                        _song = AppModel.Mp3Processor.ReadID3Tag(_originalSong.FileName, true);
                    else
                    {
                        _song = new Mp3File();
                        Mp3File.CloneMp3(_originalSong, ref _song);
                    }
                    

                    //_song = new Mp3File();
                    // //internal copy, for backup                                  
                    
                    Media.LoadedBehavior = MediaState.Manual;
                    Media.Source = new Uri(_originalSong.FileName.FullName);
                    Media.Position = TimeSpan.Zero;
                   
                    OnPropertyChanged("Song");
                }
            }
        }

        public MediaElement Media { get; set; }

        #endregion

        public ID3TagEditorViewModel(Window view, Window owner) : base(view,owner)
        {
            Media = new MediaElement();
            Media.LoadedBehavior = MediaState.Manual;
            _isPlaying = false;
        }

        #region Commands

        private RelayCommand _CmdCancel;
        public RelayCommand CmdCancel
        {
            get
            {
                if (_CmdCancel == null)
                {
                    _CmdCancel = new RelayCommand(param => OnRequestClose(), (o) => true);
                }
                return _CmdCancel;
            }
        }


        private RelayCommand _CmdFileCover;
        public RelayCommand CmdFileCover
        {
            get
            {
                if (_CmdFileCover == null)
                {
                    _CmdFileCover = new RelayCommand(param => DoCmdFileCover(), (o) => true);
                }
                return _CmdFileCover;
            }
        }


        private RelayCommand _CmdPlaySong;
        public RelayCommand CmdPlaySong
        {
            get
            {
                if (_CmdPlaySong == null)
                {
                    _CmdPlaySong = new RelayCommand(param => DoCmdPlaySong(), (o) =>
                    {
                        if (!AppModel.IsAppWorking && !_isPlaying && Song != null) return true;
                        else return false;
                    });
                }
                return _CmdPlaySong;
            }
        }

        private RelayCommand _CmdStopSong;
        public RelayCommand CmdStopSong
        {
            get
            {
                if (_CmdStopSong == null)
                {
                    _CmdStopSong = new RelayCommand(param => DoCmdStopSong(), (o) =>
                    {
                        if (!AppModel.IsAppWorking && _isPlaying && Song != null) return true;
                        else return false;
                    });
                }
                return _CmdStopSong;
            }
        }

        private RelayCommand _CmdSaveSong;
        public RelayCommand CmdSaveSong
        {
            get
            {
                if (_CmdSaveSong == null)
                {
                    _CmdSaveSong = new RelayCommand(param => DoCmdSaveSong(), (o) =>
                    {
                        if (!AppModel.IsAppWorking && Song != null) return true;
                        else return false;
                    });
                }
                return _CmdSaveSong;
            }
        }

        private RelayCommand _CmdSearchSingleCover;
        public RelayCommand CmdSearchSingleCover
        {
            get
            {
                if (_CmdSearchSingleCover == null)
                {
                    _CmdSearchSingleCover = new RelayCommand(param => DoCmdSearchSingleCover(), (o) =>
                    {
                        if (!AppModel.IsAppWorking && Song != null) return true;
                        else return false;
                    });
                }
                return _CmdSearchSingleCover;
            }
        }

        #endregion

        #region DoCommands

        public void DoCmdFileCover()
        {
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Filter = "Image Files|*.jpg;*.bmp;*.png;*.gif";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                Song.Cover = System.Drawing.Image.FromFile(fileDlg.FileName);
            }
        }


        public void DoCmdPlaySong()
        {
            Media.Play();
            _isPlaying = true;
        }

        public void DoCmdStopSong()
        {
            Media.Stop();
            _isPlaying = false;
        }

        public void DoCmdSaveSong()
        {
            try
            {
                
                bool res = AppModel.Mp3Processor.SaveID3Tag(Song);
                if (res)
                {                   
                    //copy also in memory
                     Mp3File.CloneMp3(Song, ref _originalSong);
                    _originalSong.Dirty = false; //override

                    AppModel.LogEntry("[SUCCESS] " + Song);
                   // RaiseFileSaved(Song.FileName.FullName);
                    OnRequestClose(); //close the window
                }
                else
                    MetroMessageBox.MetroShow("","File not saved",true,App.MainView,MessageIcon.Error,false);
            }
            catch (Exception e)
            {
                AppModel.LogEntry("[ERROR] ID3TagEditorViewModel: " + e.Message);
                MetroMessageBox.MetroShow("", "File not saved: " + e.Message, true, App.MainView, MessageIcon.Error, false);
            }
        }

        public void DoCmdSearchSingleCover()
        {
            //it asks which "website" to use
            SearchAddinView saw = new SearchAddinView(AppModel.SelectedSongs.Count);
            var confirm = saw.ShowDialog();
            if (confirm != true)
                return;

           Uri result = AppModel.CoverSearcher.FindSingleCover(Song);
           if (result != null)
           {               
               try
               {
                   //dowloading the single image from internet
                   Task.Factory.StartNew(()=>{
                       WebRequest req = WebRequest.Create(result);
                       WebResponse response = req.GetResponse();
                       Stream stream = response.GetResponseStream();
                       System.Drawing.Image im = System.Drawing.Image.FromStream(stream);
                       Song.ImageUrl = result;
                       Song.Cover = im;
                   });
                   MetroMessageBox.MetroShow("", "Artwork found", true, App.MainView, MessageIcon.Info, false);
               }
               catch(Exception ie)
               {
                   System.Windows.MessageBox.Show("Cover not found! cannot download the cover, error: " + ie.Message, "Shoozla", MessageBoxButton.OK, MessageBoxImage.Exclamation);
               }
               finally{
                    
               }
           }
           else
               MetroMessageBox.MetroShow(String.Empty, "Cover not found! Clean the artist and check the album name", true, App.MainView, MessageIcon.Warning);
   
        }

        #endregion

       
    }
}
